#include "preferences.h"
#include "ui_preferences.h"

Preferences::Preferences(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Preferences)
{
    ui->setupUi(this);

    InitTitlepar();
    InitTree();
    for (int i = 0; i < ui->stackedWidget_Preferences->count(); i++)
    {
        QWidget *w = ui->stackedWidget_Preferences->widget(i);
        m_widgets.append(w);
    }
    ui->stackedWidget_Preferences->setCurrentIndex(0);

    if (g_bIndependent)
    {
        ui->btn_SettingsSaveDefault->setEnabled(false);
        ui->label_SettingsSaveDefaultExplain->setEnabled(false);
        ui->checkBox_SettingsAutoSaveDefault->setEnabled(false);
        ui->checkBox_SettingsAutoSaveDefault->setChecked(false);
        ui->checkBox_SerialPortAutoConnect->setEnabled(false);
        ui->checkBox_TCPServerAutoListing->setEnabled(false);
        ui->checkBox_TCPClientAutoConnect->setEnabled(false);
        ui->label_SerialPortLastConnect->setEnabled(false);
        ui->lineEdit_SerialPortLastConnect->setEnabled(false);
        ui->label_TCPClientLastConnectIP->setEnabled(false);
        ui->lineEdit_TCPClientLastConnectIP->setEnabled(false);
        ui->label_TCPClientLastConnectPort->setEnabled(false);
        ui->lineEdit_TCPClientLastConnectPort->setEnabled(false);
        ui->checkBox_SerialPortDataAutoClear->setEnabled(false);
        ui->checkBox_TCPServerDataAutoClear->setEnabled(false);
        ui->checkBox_TCPClientDataAutoClear->setEnabled(false);
        ui->btn_update->setEnabled(false);
    }
}

Preferences::~Preferences()
{
    delete ui;
}

///
/// \brief 初始化标题栏
///
void Preferences::InitTitlepar()
{
    QDesktopWidget* desktop = QApplication::desktop();

    m_selMainWidget = new WidgetPar; //创建一个QWidget容器
    m_selMainWidget->setWindowFlags(Qt::FramelessWindowHint);//将这个QWidget的边框去掉

    this->setParent(m_selMainWidget);//重新设置这个UI界面的父对象为QWidget
    pTitleBar = new TitleBar(m_selMainWidget); //定义一个标题栏类
    //pTitleBar->showLockBtn(true);
    pTitleBar->showMaxmizeBtn(false);

    this->installEventFilter(pTitleBar);//安装事件过滤器
    QGridLayout *pLayout = new QGridLayout();//创建一个整体布局器
    pLayout->addWidget(pTitleBar);  //添加标题栏
    pLayout->addWidget(this);       //添加UI界面
    pLayout->setSpacing(0);         //布局之间的距离
    pLayout->setContentsMargins(0, 0, 0, 0); //布局器的四周边距
    m_selMainWidget->setLayout(pLayout);  //将这个布局器设置在QWidget上
    m_selMainWidget->setSizePolicy(this->sizePolicy());
    m_selMainWidget->setMaximumSize(this->maximumSize());
    m_selMainWidget->setMinimumWidth(this->minimumWidth() + 2);
    if (this->minimumHeight() + pTitleBar->height() + 10 > 60)
    {
        m_selMainWidget->setMinimumHeight(this->minimumHeight() + pTitleBar->height() + 10);
    }
    else
    {
        m_selMainWidget->setMinimumHeight(pTitleBar->height() + 2);
    }
    m_selMainWidget->setGeometry((desktop->width() - this->width())/2, (desktop->height() - this->height() - pTitleBar->height())/2, this->width(), this->height() + pTitleBar->height() + 10);
    m_selMainWidget->setTitleHeight(static_cast<uint>(pTitleBar->height()));

    connect(m_selMainWidget, &WidgetPar::CloseSignal, this, &Preferences::closeEvent);
    connect(m_selMainWidget, &WidgetPar::ShowSignal, this, &Preferences::showEvent);

    m_selMainWidget->setWindowTitle(QString("首选项设置"));
    this->setWindowTitle(QString("首选项设置"));
    setWindowIcon(QIcon(":/image/DCDA.ico"));

    ui->comboBox_SerialPortSendTextFormat->setView(new QListView(this));
}

///
/// \brief 显示界面
///
void Preferences::show()
{
    m_selMainWidget->show();
}

///
/// \brief 关闭界面
///
void Preferences::close()
{
    m_selMainWidget->close();
}

void Preferences::showEvent(QShowEvent *event)
{
    Q_UNUSED(event)
    ReadSettings();
}

///
/// \brief 读取设置参数
///
void Preferences::ReadSettings()
{
    ui->checkBox_SerialPortAutoConnect->setChecked(g_bSerialPortAutoConnect);
    ui->lineEdit_SerialPortLastConnect->setText(g_sSerialPortConnectName);
    ui->spinBox_SerialPortReadDataLimit->setValue(static_cast<int>(g_unSerialPortReadDataLimit));
    ui->checkBox_SerialPortDataAutoClear->setChecked(g_bSerialPortDataAutoClear);
    ui->spinBox_SerialPortHistoryDatanumsLimit->setValue(static_cast<int>(g_unSerialPortHistoryDatanumsLimit));
    ui->comboBox_SerialPortSendTextFormat->setCurrentIndex(g_unSerialPortSendTextFormat);

    ui->checkBox_TCPServerAutoListing->setChecked(g_bTCPServerAutoListen);
    ui->spinBox_TCPServerReadDataLimit->setValue(static_cast<int>(g_unTCPServerReadDataLimit));
    ui->checkBox_TCPServerDataAutoClear->setChecked(g_bTCPServerDataAutoClear);
    ui->spinBox_TCPServerHistoryDatanumsLimit->setValue(static_cast<int>(g_unTCPServerHistoryDatanumsLimit));

    ui->checkBox_TCPClientAutoConnect->setChecked(g_bTCPClientAutoConnect);
    ui->lineEdit_TCPClientLastConnectIP->setText(g_sTCPClientConnectIP);
    ui->lineEdit_TCPClientLastConnectPort->setText(QString::number(g_un16TCPClientConnectPort));
    ui->spinBox_TCPClientReadDataLimit->setValue(static_cast<int>(g_unTCPClientReadDataLimit));
    ui->checkBox_TCPClientDataAutoClear->setChecked(g_bTCPClientDataAutoClear);
    ui->spinBox_TCPClientHistoryDatanumsLimit->setValue(static_cast<int>(g_unTCPClientHistoryDatanumsLimit));

    ui->checkBox_SettingsAutoSaveDefault->setChecked(g_bAutoSaveSettings);
}

///
/// \brief 设置设置参数
///
void Preferences::SetSettings()
{
    g_bSerialPortAutoConnect = ui->checkBox_SerialPortAutoConnect->isChecked();
    g_unSerialPortReadDataLimit = static_cast<unsigned int>(ui->spinBox_SerialPortReadDataLimit->value());
    g_bSerialPortDataAutoClear = ui->checkBox_SerialPortDataAutoClear->isChecked();
    g_unSerialPortHistoryDatanumsLimit = static_cast<unsigned int>(ui->spinBox_SerialPortHistoryDatanumsLimit->value());
    int serialportsendtextformat = ui->comboBox_SerialPortSendTextFormat->currentIndex();
    if (serialportsendtextformat < 0) serialportsendtextformat = 0;
    g_unSerialPortSendTextFormat = serialportsendtextformat;

    g_bTCPServerAutoListen = ui->checkBox_TCPServerAutoListing->isChecked();
    g_unTCPServerReadDataLimit = static_cast<unsigned int>(ui->spinBox_TCPServerReadDataLimit->value());
    g_bTCPServerDataAutoClear = ui->checkBox_TCPServerDataAutoClear->isChecked();
    g_unTCPServerHistoryDatanumsLimit = static_cast<unsigned int>(ui->spinBox_TCPServerHistoryDatanumsLimit->value());

    g_bTCPClientAutoConnect = ui->checkBox_TCPClientAutoConnect->isChecked();
    g_unTCPClientReadDataLimit = static_cast<unsigned int>(ui->spinBox_TCPClientReadDataLimit->value());
    g_bTCPClientDataAutoClear = ui->checkBox_TCPClientDataAutoClear->isChecked();
    g_unTCPClientHistoryDatanumsLimit = static_cast<unsigned int>(ui->spinBox_TCPClientHistoryDatanumsLimit->value());

    g_bAutoSaveSettings = ui->checkBox_SettingsAutoSaveDefault->isChecked();
}

///
/// \brief 初始化QSS
///
void Preferences::InitQSS()
{
    QFile file(g_sInitQSSPath);
    bool isOK = file.open(QFile::ReadOnly);
    if (isOK)
    {
        QTextStream filetext(&file);
        QString stylesheet = filetext.readAll();
        this->setStyleSheet(stylesheet);
        m_selMainWidget->setStyleSheet(stylesheet);
    }
    file.close();
}

///
/// \brief 初始化树状图
///
void Preferences::InitTree()
{
    m_model->setHorizontalHeaderLabels(QStringList() << QStringLiteral("首选项设置"));
    QStringList strnames1;
    strnames1 << QStringLiteral("串口")
             << QStringLiteral("TCP服务端")
             << QStringLiteral("TCP客户端")
             << QStringLiteral("通用");

    QStringList strnames2;
    strnames2 << QStringLiteral("基本设置")
             << QStringLiteral("快捷发送设置")
             << QStringLiteral("互动发送设置")
             << QStringLiteral("高级循环发送设置");

    for (int i = 0; i < strnames1.count(); i++)
    {
        QString setname = strnames1.at(i);
        QStandardItem* item = new QStandardItem(setname);
        if (i != 3)
        {
            for (int j = 0; j < strnames2.size(); j++)
            {
//                w = ui->stackedWidget_Preferences->widget(5*i + j + 2);
//                wname = w->objectName();
//                qDebug() << wname;
                QString name = strnames2.at(j);
                QStandardItem* ite = new QStandardItem(name);
                item->appendRow(ite);
            }
        }
        m_model->appendRow(item);
    }
    ui->treeView_Preferences->setModel(m_model);
    ui->treeView_Preferences->setSelectionMode(QAbstractItemView::SingleSelection);// 设置整行选中，不可选择多行
    ui->treeView_Preferences->setEditTriggers(QAbstractItemView::NoEditTriggers);// 设置只读，不可编辑
    ui->treeView_Preferences->header()->hide();
    connect(ui->treeView_Preferences->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &Preferences::slotCurrentRowChanged);
    ui->treeView_Preferences->expandAll();
}

///
/// \brief 弹窗通知
/// \param strdata
///
void Preferences::inform(QString strdata)
{
    QMessageBox m_r;

    WidgetPar *wid;
    wid = new WidgetPar;
    wid->setWindowFlags(Qt::FramelessWindowHint);
    wid->setWindowModality(Qt::ApplicationModal);
    m_r.setParent(wid);
    TitleBar *titbar = new TitleBar(wid);

    titbar->showMinmizeBtn(false);
    titbar->showMaxmizeBtn(false);
    titbar->EnableCloseBtn(false);

    m_r.installEventFilter(titbar);
    QGridLayout *layout = new QGridLayout();

    layout->addWidget(titbar);  //添加标题栏
    layout->addWidget(&m_r);       //添加UI界面
    layout->setSpacing(0);         //布局之间的距离
    layout->setContentsMargins(0, 0, 0, 0); //布局器的四周边距
    wid->setLayout(layout);  //将这个布局器设置在QWidget上
    wid->setSizePolicy(m_r.sizePolicy());
    wid->setMaximumSize(m_r.maximumSize());
    wid->setMinimumWidth(m_r.minimumWidth() + 2);

    wid->setWidgetResizable(false);

    wid->move(m_selMainWidget->x() + (m_selMainWidget->width() - 150 - 3*strdata.length())/2, m_selMainWidget->y() + (m_selMainWidget->height() - (titbar->height() + 50))/2);
    wid->setTitleHeight(static_cast<uint>(titbar->height()));

    m_r.setWindowTitle("提示");
    m_r.setWindowIcon(QIcon(":/image/DCDA.ico"));
    m_r.setText(strdata);

    QFile file(g_sInitQSSPath);
    bool isOK = file.open(QFile::ReadOnly);
    if (isOK)
    {
        QTextStream filetext(&file);
        QString stylesheet = filetext.readAll();
        wid->setStyleSheet(stylesheet);
    }
    file.close();

    wid->show();
    wid->setSizePolicy(m_r.sizePolicy());
    wid->setMaximumSize(m_r.maximumSize());
    wid->setMinimumWidth(m_r.minimumWidth() + 2);
    m_r.exec();
    wid->close();
    titbar->deleteLater();
    layout->deleteLater();
    wid->deleteLater();
    titbar = nullptr;
    layout = nullptr;
    wid = nullptr;
}

///
/// \brief 弹窗询问
/// \param strdata
/// \return 返回询问结果
///
bool Preferences::AskInform(QString strdata)
{
    QMessageBox m_r;

    WidgetPar *wid;
    wid = new WidgetPar;
    wid->setWindowFlags(Qt::FramelessWindowHint);
    wid->setWindowModality(Qt::ApplicationModal);
    m_r.setParent(wid);
    TitleBar *titbar = new TitleBar(wid);

    titbar->showMinmizeBtn(false);
    titbar->showMaxmizeBtn(false);
    titbar->EnableCloseBtn(false);

    m_r.installEventFilter(titbar);
    QGridLayout *layout = new QGridLayout();

    layout->addWidget(titbar);  //添加标题栏
    layout->addWidget(&m_r);       //添加UI界面
    layout->setSpacing(0);         //布局之间的距离
    layout->setContentsMargins(0, 0, 0, 0); //布局器的四周边距
    wid->setLayout(layout);  //将这个布局器设置在QWidget上


    wid->setWidgetResizable(false);

    wid->setTitleHeight(static_cast<uint>(titbar->height()));

    m_r.setWindowTitle("提示");
    m_r.setWindowIcon(QIcon(":/image/DCDA.ico"));
    m_r.setText(strdata);
    m_r.addButton(tr("确认"), QMessageBox::ActionRole);
    m_r.addButton(tr("取消"), QMessageBox::ActionRole);

    wid->setSizePolicy(m_r.sizePolicy());
    wid->setMaximumSize(m_r.maximumSize());
    wid->setMinimumWidth(m_r.minimumWidth() + 2);

    int length = strdata.length();
    if (length > 74)
    {
        length = 74;
    }
    //qDebug() << "this x:" << m_selMainWidget->x() << ", y:" << m_selMainWidget->y() << ", width:" << m_selMainWidget->width() << ", height:" << m_selMainWidget->height();
    //qDebug() << "m_r width:" << m_r.width() << ", height:" << m_r.height() << ", titbar height:" << titbar->height();
    wid->move(m_selMainWidget->x() + (m_selMainWidget->width() - 150 - 3*length)/2, m_selMainWidget->y() + (m_selMainWidget->height() - (titbar->height() + 50))/2);

    //qDebug() << "wid x:" << wid->x() << ", y" << wid->y() << ", width" << wid->width() << ", height" << wid->height();

    QFile file(g_sInitQSSPath);
    bool isOK = file.open(QFile::ReadOnly);
    if (isOK)
    {
        QTextStream filetext(&file);
        QString stylesheet = filetext.readAll();
        wid->setStyleSheet(stylesheet);
    }
    file.close();

    if (pTitleBar->getLockState())
    {
        Qt::WindowFlags m_flags = wid->windowFlags();
        wid->setWindowFlags(m_flags | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
    }
    wid->show();
    wid->setSizePolicy(m_r.sizePolicy());
    wid->setMaximumSize(m_r.maximumSize());
    wid->setMinimumWidth(m_r.minimumWidth() + 2);
    int isok = m_r.exec();
    wid->close();
    titbar->deleteLater();
    layout->deleteLater();
    wid->deleteLater();
    titbar = nullptr;
    layout = nullptr;
    wid = nullptr;
    if (isok == 1)
    {
        return false;
    }
    else
    {
        return true;
    }
}

///
/// \brief 获取选择的某个菜单项
/// \param current
/// \param previous
///
void Preferences::slotCurrentRowChanged(const QModelIndex &current, const QModelIndex &previous)
{
    Q_UNUSED(previous)
    QModelIndex index = current.sibling(current.row(), 0);
    int parrow = index.parent().row();
    QStandardItem *modelitem = m_model->itemFromIndex(index);
    QString strname = modelitem->text();
    int num = ModelGetWidget(parrow, strname);
    if (num == -1)
    {
        ui->stackedWidget_Preferences->setCurrentIndex(0);
    }
    else
    {
        ui->stackedWidget_Preferences->setCurrentWidget(m_widgets[num]);
    }
}

///
/// \brief 获取object的值
/// \param name
/// \return
///
int Preferences::ModelGetWidget(int parrow, QString name)
{
    QString objname;
    if (parrow == -1)
    {
        if (name == "串口")
        {
            objname = "page_SerialPort";
        }
        else if (name == "TCP服务端")
        {
            objname = "page_TCPServer";
        }
        else if (name == "TCP客户端")
        {
            objname = "page_TCPClient";
        }
        else if (name == "通用")
        {
            objname = "page_Default";
        }
    }
    else
    {
        if (name == "基本设置")
        {
            switch (parrow) {
            case 0: objname = "page_SerialPortDefault"; break;
            case 1: objname = "page_TCPServerDefault"; break;
            case 2: objname = "page_TCPClientDefault"; break;
            }
        }
        else if (name == "快捷发送设置")
        {
            switch (parrow) {
            case 0: objname = "page_SerialPortQuickSend"; break;
            case 1: objname = "page_TCPServerQuickSend"; break;
            case 2: objname = "page_TCPClientQuickSend"; break;
            }
        }
        else if (name == "互动发送设置")
        {
            switch (parrow) {
            case 0: objname = "page_SerialPortInteract"; break;
            case 1: objname = "page_TCPServerInteract"; break;
            case 2: objname = "page_TCPClientInteract"; break;
            }
        }
        else if (name == "高级循环发送设置")
        {
            switch (parrow) {
            case 0: objname = "page_SerialPortSeniorCycle"; break;
            case 1: objname = "page_TCPServerSeniorCycle"; break;
            case 2: objname = "page_TCPClientSeniorCycle"; break;
            }
        }
    }
    if (!objname.isEmpty())
    {
        for (int i = 0; i < m_widgets.count(); i++)
        {
            if (m_widgets[i]->objectName() == objname)
            {
                return i;
            }
        }
    }
    return -1;
}

///
/// \brief 关闭
///
void Preferences::on_btn_Close_clicked()
{
    m_selMainWidget->close();
    //emit CloseSignal();
}

///
/// \brief 应用
///
void Preferences::on_btn_Renovate_clicked()
{
    SetSettings();
}

///
/// \brief 确定
///
void Preferences::on_btn_Setting_clicked()
{
    SetSettings();
    on_btn_Close_clicked();
}

///
/// \brief 串口收发数据清零
///
void Preferences::on_btn_SerialPortDataClear_clicked()
{
    g_unSerialPortReadnums = 0;
    g_unSerialPortSendnums = 0;
    emit ReadSendUpdateSignal();
}

///
/// \brief TCPServer收发数据清零
///
void Preferences::on_btn_TCPServerDataClear_clicked()
{
    g_unTCPServerReadnums = 0;
    g_unTCPServerSendnums = 0;
    emit ReadSendUpdateSignal();
}

///
/// \brief TCPClient收发数据清零
///
void Preferences::on_btn_TCPClientDataClear_clicked()
{
    g_unTCPClientReadnums = 0;
    g_unTCPClientSendnums = 0;
    emit ReadSendUpdateSignal();
}

///
/// \brief 打开串口高级发送编辑器
///
void Preferences::on_btn_SerialPortSeniorCycleOpen_clicked()
{
    emit SerialPortSeniorCycleOpenSignal();
}

///
/// \brief 打开TCP服务端高级发送编辑器
///
void Preferences::on_btn_TCPServerSeniorCycleOpen_clicked()
{
    emit TCPServerSeniorCycleOpenSignal();
}

///
/// \brief 打开TCP客户端高级发送编辑器
///
void Preferences::on_btn_TCPClientSeniorCycleOpen_clicked()
{
    emit TCPClientSeniorCycleOpenSignal();
}

///
/// \brief 导出串口快捷发送
///
void Preferences::on_btn_SerialPortQuickSendDerive_clicked()
{
    QString path = QFileDialog::getSaveFileName(this, "导出串口快捷发送", "/", "XML(*.xml)");
    if (!path.isEmpty())
    {
        emit SerialPortQuickSendDeriveSignal(path);
    }
}

///
/// \brief 导入串口快捷发送
///
void Preferences::on_btn_SerialPortQuickSendInduct_clicked()
{
    QString path = QFileDialog::getOpenFileName(this, "导入串口快捷发送", "/", "XML(*.xml)");
    if (!path.isEmpty())
    {
        emit SerialPortQuickSendInductSignal(path);
    }
}

///
/// \brief 导出串口交互发送
///
void Preferences::on_btn_SerialPortInteractDerive_clicked()
{
    QString path = QFileDialog::getSaveFileName(this, "导出串口交互发送", "/", "XML(*.xml)");
    if (!path.isEmpty())
    {
        emit SerialPortInteractDeriveSignal(path);
    }
}

///
/// \brief 导入串口交互发送
///
void Preferences::on_btn_SerialPortInteractInduct_clicked()
{
    QString path = QFileDialog::getOpenFileName(this, "导入串口交互发送", "/", "XML(*.xml)");
    if (!path.isEmpty())
    {
        emit SerialPortInteractInductSignal(path);
    }
}

///
/// \brief 导出TCP服务端快捷发送
///
void Preferences::on_btn_TCPServerQuickSendDerive_clicked()
{
    QString path = QFileDialog::getSaveFileName(this, "导出TCP服务端快捷发送", "/", "XML(*.xml)");
    if (!path.isEmpty())
    {
        emit TCPServerQuickSendDeriveSignal(path);
    }
}

///
/// \brief 导入TCP服务端快捷发送
///
void Preferences::on_btn_TCPServerQuickSendInduct_clicked()
{
    QString path = QFileDialog::getOpenFileName(this, "导入TCP服务端快捷发送", "/", "XML(*.xml)");
    if (!path.isEmpty())
    {
        emit TCPServerQuickSendInductSignal(path);
    }
}

///
/// \brief 导出TCP服务端交互发送
///
void Preferences::on_btn_TCPServerInteractDerive_clicked()
{
    QString path = QFileDialog::getSaveFileName(this, "导出TCP服务端交互发送", "/", "XML(*.xml)");
    if (!path.isEmpty())
    {
        emit TCPServerInteractDeriveSignal(path);
    }
}

///
/// \brief 导入TCP服务端交互发送
///
void Preferences::on_btn_TCPServerInteractInduct_clicked()
{
    QString path = QFileDialog::getOpenFileName(this, "导入TCP服务端交互发送", "/", "XML(*.xml)");
    if (!path.isEmpty())
    {
        emit TCPServerInteractInductSignal(path);
    }
}

///
/// \brief 导出TCP客户端快捷发送
///
void Preferences::on_btn_TCPClientQuickSendDerive_clicked()
{
    QString path = QFileDialog::getSaveFileName(this, "导出TCP客户端快捷发送", "/", "XML(*.xml)");
    if (!path.isEmpty())
    {
        emit TCPClientQuickSendDeriveSignal(path);
    }
}

///
/// \brief 导入TCP客户端快捷发送
///
void Preferences::on_btn_TCPClientQuickSendInudct_clicked()
{
    QString path = QFileDialog::getOpenFileName(this, "导入TCP客户端快捷发送", "/", "XML(*.xml)");
    if (!path.isEmpty())
    {
        emit TCPClientQuickSendInductSignal(path);
    }
}

///
/// \brief 导出TCP客户端交互发送
///
void Preferences::on_btn_TCPClientInteractDerive_clicked()
{
    QString path = QFileDialog::getSaveFileName(this, "导出TCP客户端交互发送", "/", "XML(*.xml)");
    if (!path.isEmpty())
    {
        emit TCPClientInteractDeriveSignal(path);
    }
}

///
/// \brief 导入TCP客户端交互发送
///
void Preferences::on_btn_TCPClientInteractInduct_clicked()
{
    QString path = QFileDialog::getOpenFileName(this, "导入TCP客户端交互发送", "/", "XML(*.xml)");
    if (!path.isEmpty())
    {
        emit TCPClientInteractInductSignal(path);
    }
}

///
/// \brief 保存为默认设置
///
void Preferences::on_btn_SettingsSaveDefault_clicked()
{
    SetSettings();
    emit SaveSettingsSianal();
    inform("保存成功！");
}

///
/// \brief 还原为初始默认设置
///
void Preferences::on_btn_ResetSettings_clicked()
{
    bool isOK = AskInform("还原为初始默认设置将无法撤销，已设置的功能或数据将初始化或清空！请谨慎操作！是否继续？");
    if (isOK)
    {
        isOK = AskInform("请再次确认！是否继续将软件还原为初始默认设置？");
        if (isOK)
        {
            emit ResetSettingsSignal();
            inform("已还原为默认初始设置！");
        }
    }
}

///
/// \brief 检查更新
///
void Preferences::on_btn_update_clicked()
{
    checkUpdateShow();
}

///
/// \brief 显示更新软件
///
void Preferences::checkUpdateShow()
{
    if (m_proUpdate == nullptr)
    {
        QString updatename;
#if defined (Q_OS_WIN)
        updatename = "DCDA_Renew.exe";
#elif defined (Q_OS_LINUX)
        updatename = "DCDA_Renew";
#else
        inform("当前运行环境暂不支持该软件的更新功能");
        return ;
#endif
        QString appPath = qApp->applicationDirPath();
        bool exist = QFile::exists(appPath + "/" + updatename);
        if (!exist)
        {
            inform("缺少更新软件，请到 <a href=\"https://lijianxun.cn/dcda/\">https://lijianxun.cn/dcda/</a> 网站手动下载更新");
            return ;
        }
        m_proUpdate = new QProcess(this);
        m_proUpdate->setReadChannel(QProcess::StandardOutput);
        connect(m_proUpdate, SIGNAL(readyRead()), this, SLOT(ReadFromUpdate()));
        QStringList argu;
        argu.append(g_sInitQSSPath);
#if defined (Q_OS_WIN)
        argu.append(qAppName() + ".exe");
#elif defined (Q_OS_LINUX)
        argu.append(qAppName());
#else
        inform("Error：可能不支持自动更新，建议手动更新");
        return ;
#endif
        m_proUpdate->setProgram("./" + updatename);
        m_proUpdate->setArguments(argu);
        m_proUpdate->open();
    }
    else if (m_proUpdate->isOpen())
    {
        m_proUpdate->close();
        m_proUpdate->open();
    }
}

void Preferences::ReadFromUpdate()
{
    if (!m_proUpdate) return ;
    //m_proUpdate->waitForReadyRead();
    QByteArray output = m_proUpdate->readAllStandardOutput();
    qDebug() << "read process output:" << output;
    //inform(output);
    if (output == "exit\r\n")
    {
        emit ExitSignal();
    }
}
